package com.liu.config;

import com.liu.mapper.SysRoleMapper;
import com.liu.mapper.SysUserMapper;
import com.liu.pojo.SysRole;
import com.liu.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import sun.rmi.runtime.Log;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails = null;
        try {
            List<SysUser> sysUserList = sysUserMapper.selectByUserNameSysUsers(username);
            if(sysUserList == null){
                throw new UsernameNotFoundException("该用户找不到");
            }
            SysUser sysUser = sysUserList.get(0);
            String roles = sysRoleMapper.getRoleNameById(sysUser.getId());
            List<GrantedAuthority> authorities = new ArrayList<>();
            String [] arrstr = roles.split(";");
            if(roles !=null && !"".equals(arrstr)){
                for(String role :arrstr){
                    authorities.add(new SimpleGrantedAuthority(role));
                }
            }
            userDetails = new User(username, new BCryptPasswordEncoder().encode(sysUser.getPassword()),true,true,true,true,authorities);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return userDetails;
    }

}
